package com.neuedu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.common.Result;
import com.neuedu.pojo.User;
import com.neuedu.service.UserService;
import com.neuedu.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;


    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户登录功能
     *
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result<User> login(HttpServletRequest request, @RequestBody User user) {
        //1.将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

//        System.out.println(password);


        //2.根据页面提交的用户名phoneNumber查询数据库
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhoneNumber, user.getPhoneNumber());
        User userTmp = userService.getOne(lqw);

        //3.如果没有查询到返回登录失败结果
        if (null == userTmp) {
            return Result.error("用户未注册");
        }

        //4.密码比对，如果不一致返回登录失败结果
        if (!userTmp.getPassword().equals(password)) {
            return Result.error("登录失败");
        }

        //5.查看用户状态，如果为已禁用状态，则返回用户已禁用结果
        if (!userTmp.getStatus()) {
            return Result.error("用户已被封号");
        }

        //6.登录成功，将用户id存入Session并返回登录成功结果
        request.getSession().setAttribute("user", userTmp.getId());
        return Result.success(userTmp);
    }

    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        //清理Session中保存的当前登录用户的id
        request.getSession().removeAttribute("user");
        return Result.success("退出成功");
    }

    /**
     * 新增用户功能
     *
     * @param request
     * @param user
     * @return
     */
    @PostMapping
    public Result<String> save(HttpServletRequest request, @RequestBody User user) {
        //设置用户创建时间和更新时间
//        user.setCreateTime(LocalDateTime.now());
//        user.setUpdateTime(LocalDateTime.now());

        //设置初始密码为123456，并进行md5加密
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        user.setPassword(password);
        user.setStatus(true);
        user.setIsVip(false);

        //获取当前操作用户的id
//        Long empId = (Long) request.getSession().getAttribute("user");
//        user.setCreateUser(empId);
//        user.setUpdateUser(empId);
        userService.save(user);
        return Result.success("新增用户成功");
    }

    /**
     * 用户信息分页查询（同时可以根据手机号和用户名进行模糊匹配）
     *
     * @param page
     * @param pageSize
     * @param query 用户名或手机号或姓名
     * @return
     */
    @GetMapping("/page")
    public Result<Page<User>> page(int page, int pageSize, String query) {
        log.info("page={}, pageSize={}, query={}", page, pageSize, query);
        //构造分页构造器
        Page<User> pageInfo = new Page<User>(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(null != query, User::getUsername, query)
                .or().like(null != query, User::getPhoneNumber, query)
                .or().like(null != query, User::getName, query);
        queryWrapper.orderByDesc(User::getPhoneNumber);
        userService.page(pageInfo, queryWrapper);
        log.info("total:{}", pageInfo.getTotal());
        return Result.success(pageInfo);
    }

    /**
     * 更新用户信息
     *
     * @param request
     * @param user
     * @return
     */
    @PutMapping
    public Result<String> update(HttpServletRequest request, @RequestBody User user) {
//        user.setUpdateTime(LocalDateTime.now());
//        user.setUpdateUser((long)request.getSession().getAttribute("user"));

        //重置用户密码
        if(user.getPassword() != null) {
            String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(password);
        }

        userService.updateById(user);
        return Result.success("用户信息修改成功");
    }

    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable long id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

    /**
     * 根据id进行删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteById(@PathVariable long id) {
        userService.removeById(id);
        return Result.success("删除用户信息成功");
    }

    /**
     * 发送验证码功能
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session) {
        //接收用户的手机号
        String phoneNumber = user.getPhoneNumber();
        //创建验证码
        if (null != phoneNumber) {
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
            log.info("code:{}",code);
            //调用阿里云的api发送验证码
            //SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phoneNumber, code);

//            session.setAttribute(phoneNumber, code);

            //使用redis保存验证码5分钟
            //redisTemplate.opsForValue().set(phoneNumber, code, 5, TimeUnit.MINUTES);
            return Result.success("手机验证码短信发送成功");
        }
        return Result.error("手机验证码短信发送失败");
    }

    @PostMapping("/loginByCode")
    public Result<User> login(@RequestBody Map<String, String> map, HttpSession session, HttpServletRequest request) {
        //获取手机号
        String phoneNumber = map.get("phoneNumber");
        //获取验证码
        String code = map.get("code");
        // 获取用户名
        String username = map.get("username");

        //比对验证码（页面提交的验证码和session中验证码进行比对）
        Object codeInSession = session.getAttribute(phoneNumber);

        //从redis中获取验证码
//        Object codeInSession = redisTemplate.opsForValue().get(phoneNumber);

        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        if (null != codeInSession && code.equals(codeInSession)){
            //比对成功，成功登录
            //登录成功后，删除redis中对应的key
            //redisTemplate.delete(phoneNumber);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhoneNumber, phoneNumber);
            User user = userService.getOne(queryWrapper);
            // 此用户已存在，返回错误信息
            if(user != null){
                user.setPassword(password);
                userService.updateById(user);
                return Result.error("您已经注册过账号，已将您密码重置为123456，请返回登录");
            }
            //新用户自动注册
            if(user == null){
                user = new User();
                user.setPhoneNumber(phoneNumber);
                //设置初始密码为123456，并进行md5加密

                user.setPassword(password);
                user.setUsername(username);
                user.setStatus(true);
                user.setIsVip(false);
                userService.save(user);
            }
            // 注入user信息
            Long userId = user.getId();
            user.setCreateUser(userId);
            user.setUpdateUser(userId);

            //保存登录状态
            request.getSession().setAttribute("user", userId);
            return Result.success(user);
        }
        return Result.error("登录失败");
    }
}
